package kyssion.leetcode.num151_200;

public class code151_翻转字符串里的单词 {

    public static void main(String[] args) {
        System.out.println(new code151_翻转字符串里的单词().reverseWords(
                " oooo o"
        ));
    }

    public String reverseWords(String s) {
        if(s==null){
            return null;
        }
        int start = -1;
        int speed = 0;
        s += " ";
        StringBuilder st = new StringBuilder();
        for (int a = 0; a < s.length(); a++) {
            if (s.charAt(a) != ' ') {
                speed++;
            } else {
                if (speed > 0) {
                    if (st.length() == 0) {
                        st.append(s, start + 1, start + speed + 1);
                    } else {
                        st.append(" ").append(s, start + 1, start + speed + 1);
                    }
                }
                start = a;
                speed = 0;
            }
        }
        String[] item = st.toString().split(" ");
        st = new StringBuilder();
        for (int a=item.length-1;a>=0;a--){
            if(st.length()==0){
                st.append(item[a]);
            }else{
                st.append(" ").append(item[a]);
            }
        }
        return st.toString();
    }

    public String reverseWords2(String s) {
        s =s.trim();
        String[] arr = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for(int i=arr.length-1;i>=0;i--) {
            if(!"".equals(arr[i])) {
                sb.append(arr[i]).append(" ");
            }
        }
        return sb.toString().trim();
    }
}
